<template>
  <div class="page mobileValidate">
    <div class="scroll-view">
      <customHeader middleTitle="商户签约验证" @leftCallBack="back"></customHeader>
      <fxActivityProtocol ref="fxActivityProtocol"></fxActivityProtocol>
      <div class="page-body">
        <div class="section" v-show="step===1">
          <div
            class="form-title"
          >请输入{{queryParams.bankName}}{{CommonUtil.encryptionBankCardNo(bankCardNo)}}银行卡预留的手机号</div>
          <ul class="form-style">
            <li>
              <span>手机号</span>
              <div>
                <inputClear placeholder="请输入手机号" v-model="contactMobile" :maxlength="11" :max="11"></inputClear>
              </div>
            </li>
          </ul>
          <div class="btn-wrap">
            <div class="btn" @click="nextStep">下一步</div>
          </div>
        </div>
        <div class="section" v-show="step===2">
          <div class="form-title">授权码以短信形式发送至您的手机号{{contactMobile}}</div>
          <ul class="form-style">
            <li>
              <span>授权码</span>
              <div>
                <inputClear placeholder="请输入授权码" v-model="code"></inputClear>
              </div>
              <div>
                <div v-if="!waitTime" class="getCode" @click="getCode">重新获取</div>
                <div v-if="waitTime" class="getCode disabled">{{waitTime+'秒后重发'}}</div>
              </div>
            </li>
          </ul>
          <div class="protocol">
            <i :class="protocolChecked?'zhk-ty':'zhk-wxz'" @click="protocolCheck"></i>
            我已阅读同意
            <span class="link" @click="openProtocol()">《营销服务协议》</span>
            <span
              class="link"
              @click="linkToProtocol(validateData?validateData['signUrl']:'')"
            >《商户分账协议》</span>
          </div>
          <div class="btn-wrap">
            <div class="btn" :class="{disabled:!code||!protocolChecked}" @click="submit">提交</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import inputClear from "../../components/inputClear/inputClear";
import fxActivityProtocol from "../fxActivitySigning/fxActivityProtocol";
import { Toast } from "mint-ui";
import jsBridge from "../../tools/jsBridge.js";
export default {
  name: "mobileValidate",
  data() {
    return {
      CommonUtil: CommonUtil,
      queryParams: null,
      protocolChecked: false,
      code: "",
      waitTime: 0,
      timerId: "",
      step: 1,
      contactMobile: "",
      bankCardNo: "",
      validateData: null,
    };
  },

  methods: {
    back() {
      if (this.step > 1) {
        this.prevStep();
      } else {
        this.$router.back();
      }
    },
    openProtocol() {
      this.$refs.fxActivityProtocol.popupShow();
    },
    linkToProtocol(url) {
      if (!url) {
        Toast("未取到协议地址");
      } else {
        jsBridge.openWindow({
          needTitle: true,
          url: url,
          target: "server",
        });
      }
    },
    protocolCheck() {
      this.protocolChecked = !this.protocolChecked;
    },
    nextStep() {
      if (!this.contactMobile) {
        Toast('必须填写手机号');
        return;
      }
      if (!CommonUtil.checkMobile(this.contactMobile)) {
        Toast('请填写正确的手机号');
        return;
      }
     
      if (this.waitTime === 0) {
        this.getCode(()=>{ this.step = this.step + 1;});
      }else{
        this.step = this.step + 1;
      }
    },
    prevStep() {
      this.step = this.step - 1;
    },
    reduceTime: function () {
      if (this.waitTime > 0) {
        this.timerId = setTimeout(() => {
          this.waitTime--;
          this.reduceTime();
        }, 1000);
      } else {
        clearTimeout(this.timerId);
        this.timerId = null;
      }
    },
    submit() {
      if (!this.protocolChecked) {
        Toast('请先阅读并同意协议内容');
        return;
      }
      if (!this.code) {
        Toast('请输入授权码');
        return;
      }
      this.updateMsgState();

    },
    //更改消息状态
    updateMsgState() {
      if(!this.validateData.contractNo){
         Toast("未获取到协议");
      }
      let param = {
        shopId: this.queryParams.shopId,
        msgId: this.queryParams.msgId,
        msgStatus: 1,//1：同意
        msgTitleType: this.queryParams.msgTitleType,
        openId: this.queryParams.openId,
        needOpenMarketing: this.queryParams.needOpenMarketing,
        marketActivityModel: {
          operate: "0",//0走富友 1直接改状态 
          status: this.queryParams.marketActivityModel.status,
          mchntAllowcateSignModel: {
            shopId: this.queryParams.shopId,
            merchantId: this.validateData.merchantId,
            accountType: this.queryParams.accountType,
            verifyNo: this.code,
            verifyAmt: "",
            contractNo: this.validateData.contractNo
          },
        },
      };
      this.ajax({
        url: "/newapp/AppMsg/updateMsgState.do",
        type: "post",
        data: param,
        controlLoading: true
      }).then(res => {
        if (res.success) {
          Toast({
            message: '处理成功',
            iconClass: 'icon icon-success'
          });
          if (this.queryParams.needOpenMarketing == 4) {
            //needOpenMarketing是否需要开通（变更）分账（新增） 0 不需要开通分账 1 支付宝商户号开通分账 2.微信商户号开通分账 3.同一商户号开通分账 4.不同商户号开通分账
            this.$router.back();
          } else {
            this.$router.go(-3);
          }
        } else {
          Toast(res.msg);
        }
      })
        .catch(err => {

        });
    },
    //发送授权码
    getCode(callBack) {
      this.ajax({
        url: `/newapp/AppMsg/getMarketingOauthCode.do?payType=${this.queryParams.payType}&marketingId=${this.queryParams.openId}&shopId=${this.queryParams.shopId}&msgId=${this.queryParams.msgId}&phoneNumber=${this.contactMobile}`,
        type: "get",
        controlLoading: true
      })
        .then(result => {
          if (result.success.toString() == "true") {
            this.validateData = result.resultObject;
            this.waitTime = 60*3;
            this.reduceTime();
            if(callBack&&typeof callBack=="function"){
              callBack();
            }
            window.localStorage&&window.localStorage.setItem("MarketingOauthCodeTimer",new Date().getTime());
          } else {
            Toast(result.msg);
          }
        })
        .catch(err => {

        });
    },
    //是否已经生成协议,如果已经生成协议则直接跳到下一步
    hasProtocol() {
      this.ajax({
        url: `/newapp/AppMsg/allowcateAgreementCheck.do?merchantId=${this.queryParams.merchantId}`,
        type: "get",
        controlLoading: false
      })
        .then(result => {
          if (result.success.toString() == "false") {//没有生成协议

          } else {
            //生成过协议
            if (result.resultObject && result.resultObject['contractNo']) {
              this.validateData = result.resultObject;
              if(result.resultObject&&result.resultObject['signPhone']){
                this.contactMobile = result.resultObject['signPhone'];
              }
              this.waitTime = 60*3;
              if(window.localStorage){
                 let timestamp= window.localStorage.getItem("MarketingOauthCodeTimer");
                 if(timestamp){
                   timestamp=Number(timestamp);
                   let second= (new Date().getTime()-timestamp)/1000<60*3?60*3-Math.ceil((new Date().getTime()-timestamp)/1000):0;
                   this.waitTime=second;
                 }
              }
              this.reduceTime();
              this.step = 2;
            }
          }
        })
        .catch(err => {

        });
    }

  },
  destroyed() {
    clearTimeout(this.timerId);
  },
  created() {
    this.queryParams = this.$route.query;
    this.contactMobile = this.$route.query.contactMobile;
    this.bankCardNo = this.$route.query.bankCardNo;
    this.hasProtocol();
  },
  components: {
    customHeader,
    inputClear,
    fxActivityProtocol
  },

};
</script>
<style lang='scss' scoped>
@import "fxActivitySigning";
</style>
